const { validate } = require('validate.js')
const typeDao = require("../dao/operation/blogTypeDao")
const { blogCountByBlogType } = require("../dao/operation/blogDao")
const { formatResponse, processingData } = require("../utils/tool")
const { ValidationError } = require("../utils/error")


/**
 * 新增
 * @param {*} newType 
 */
module.exports.addBlogType = async function(newType) {
    // 数据验证规则
    const blogTypeRule = {
        name: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        order: {
            presence: {
                allowEmpty: false
            }
        }
    }

    const result = await validate.validate(newType, blogTypeRule)
    if (!result) {
        newType.articleCount = 0 // 默认没有文章
        const newresult = await typeDao.addType(newType)
        return formatResponse(0, "", newresult)
    } else {
        return new ValidationError("数据验证失败，请填写正确的数据").toResponseJSONError()
    }
}

/**
 * 查询所有
 * @param {*} newType 
 */
module.exports.findAllBlogType = async function(newType) {
    const result = await typeDao.allType()
    const obj = formatResponse(0, "", processingData(result))
    obj.data.sort((a, b) => a.order - b.order)
    return obj
}


/**
 * 查询单个
 * @param {*} id 
 */
module.exports.findOneBlogType = async function(id) {

    return formatResponse(0, "", await typeDao.oneType(id))
}

/**
 * 删除单个
 * @param {*} id 
 */
module.exports.deleteBlogType = async function(id) {
    const count = await blogCountByBlogType(id);

    await typeDao.deleteType(id)
    return formatResponse(0, "", count)
}

/**
 * 修改单个
 * @param {*} id 
 */
module.exports.putBlogType = async function(id, info) {
    if (id && JSON.stringify(info) !== "{}") {
        return formatResponse(0, "", await typeDao.updateType(id, info))
    } else {
        return new ValidationError("数据验证失败，请填写正确的数据").toResponseJSONError()
    }

}